package com.renren.webmaven2.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.renren.webmaven2.util.RandomValidateCode;

/**
 */
@Controller
public class RandomCodeController extends LocalBaseController {

	@RequestMapping(value = "test")
	public String test(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "home";
	}

	@RequestMapping(value = "codeImage")
	public void codeImage(HttpServletRequest request, HttpServletResponse response, Model model) {
		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		try {
			randomValidateCode.getRandcode(request, response);// 输出图片方法
		} catch (Exception e) {
			logger.error(e);
		}
	}

	@RequestMapping(value = "/testCode", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> testCode(HttpServletRequest request) throws InterruptedException {
		String code = request.getParameter("code");
		String vCode = (String) request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (StringUtils.isBlank(code) || !code.equals(vCode)) {
			modelMap.put("result", "0");
		} else {
			modelMap.put("result", 1);
		}
		return modelMap;

	}

}
